package com.blogSystem.user.controller;

        import com.alibaba.fastjson.JSON;
        import com.alibaba.fastjson.JSONObject;
        import com.blogSystem.user.dao.ConcerMapper;
        import com.blogSystem.user.dao.UserDao;
        import com.blogSystem.user.pojo.Concer;
        import com.blogSystem.user.pojo.User;
        import com.blogSystem.user.service.UserService;
        import com.blogSystem.user.util.UpLoad;
        import entity.Result;
        import entity.StatusCode;
        import io.jsonwebtoken.Claims;
        import jdk.net.SocketFlow;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.data.domain.Page;
        import org.springframework.data.domain.PageRequest;
        import org.springframework.data.domain.Pageable;
        import org.springframework.data.redis.core.RedisTemplate;
        import org.springframework.web.bind.annotation.*;
        import org.springframework.web.multipart.MultipartFile;
        import sun.misc.Request;
        import util.JwtUtil;

        import javax.servlet.http.HttpServletRequest;
        import javax.servlet.http.HttpSession;
        import java.util.HashMap;
        import java.util.LinkedHashMap;
        import java.util.List;
        import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/user")


public class UserController {

  @Autowired
  private ConcerMapper concerMapper;

  @Autowired
  private RedisTemplate redisTemplate;
  @Autowired
  private UserService userService;

  @Autowired
  private HttpServletRequest request;
  @Autowired
  private HttpSession session;
@Autowired
private UserDao userDao;
  /**
   * 发送验证码用于注册
   */
  @RequestMapping(value = "/sendsms", method = RequestMethod.POST)
  public Result sendSms(@RequestBody Map map) {
    String mobile = (String) map.get("param");
    if (userService.mobileIsRep(mobile)) {
      return new Result(false, StatusCode.HAS, "手机号已被注册");
    }
    System.out.println(mobile);
    userService.sendSms(mobile);
    return new Result(true, StatusCode.OK, "发送成功");
  }

  /**
   * 用户注册
   */
  @RequestMapping(value = "/reister", method = RequestMethod.PUT)
  public Result regsit(@RequestBody Map map) {
    String code = (String) map.get("code");
    LinkedHashMap linkedHashMap = (LinkedHashMap) map.get("user");
    String json = new JSONObject().toJSONString(linkedHashMap);
    User user = JSONObject.parseObject(json, User.class);
    //得到缓存中的验证码
    String key = "checkcode_" + user.getMobile();
    if (redisTemplate.opsForValue().get(key) == null) {
      return new Result(false, StatusCode.ERROR, "请获取手机验证码");
    }
    String checkCodeRedis = (String) redisTemplate.opsForValue().get(key);
    System.out.println(key + ":" + checkCodeRedis);
    if (checkCodeRedis.isEmpty()) {
      return new Result(false, StatusCode.ERROR, "请获取手机验证码");
    }
    if (!checkCodeRedis.equals(code)) {
      return new Result(false, StatusCode.ERROR, "验证码有误");
    }
    if (userService.userNameIsRep(user.getUsername())) {
      return new Result(false, StatusCode.HAS, "用户名已存在");
    }
    user.setRole("ROLE_USER");
    userService.add(user);
    return new Result(true, StatusCode.OK, "注册成功");
  }

  /**
   * 用户登录
   * @param user
   * @return
   */
  // @RequestMapping(value = "/login",method = RequestMethod.POST)
  // public Result logIn(@RequestBody User user) {
        /*User userLogin = userService.login(user);
        if (userLogin == null) {
            return new Result(false, StatusCode.LOGINERROR, "用户名或密码错误");
        } else {
            System.out.println(userLogin.getRole());

            String token = jwtUtil.createJWT(userLogin.getId(), userLogin.getUsername(), userLogin.getRole());
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("token", token);
            map.put("role", userLogin.getRole());
            return new Result(true, StatusCode.OK, "登录成功", map);
        }*/

//   }

  /**
   * 用户信息
   *
   * @param id
   * @return
   */
  @RequestMapping(value = "/info/{id}", method = RequestMethod.GET)
  public Result Info(@PathVariable String id) {
    User user = userService.findById(id);

    if (user == null) {
      return new Result(false, StatusCode.LOGINERROR, "该用户未查到");
    } else {
      return new Result(true, StatusCode.OK, "查询成功", user);
    }
  }

  /**
   * 修改用户名
   *
   * @param user
   * @return
   */

  @RequestMapping(value = "/changename", method = RequestMethod.PUT)
  public Result changename(@RequestBody User user) {

    JwtUtil jwtUtil = new JwtUtil();
    String token = (String) request.getAttribute("token");
    if (token == null || "".equals(token)) {
      return new Result(false, StatusCode.ACCESSERROR, "权限不足！");
    }
    Claims claims = jwtUtil.parseJWT(token);
    /*if (!claims.getId().equals(user.getId())) {

      return new Result(false, StatusCode.ACCESSERROR, "权限不足！");
    }*/
    if (userService.changeName(user.getId(), user)) {
      return new Result(true, StatusCode.OK, "修改成功");
    }
    System.out.println(claims.getId());
    System.out.println("1111111111111111111111");

    return new Result(false, StatusCode.HAS, "用户名已存在");
  }

  /**
   * 发送手机验证码用于修改密码
   *
   * @param user
   * @return
   */
  @RequestMapping(value = "/sendsmschange", method = RequestMethod.POST)
  public Result sendSmsChange(@RequestBody User user) {
    JwtUtil jwtUtil = new JwtUtil();
    String token = (String) request.getAttribute("token");
    if (token == null || "".equals(token)) {
      return new Result(false, StatusCode.ACCESSERROR, "权限不足！");
    }
    Claims claims = jwtUtil.parseJWT(token);
    if (!claims.getId().equals(user.getId())) {
      return new Result(false, StatusCode.ACCESSERROR, "权限不足！");
    }
    userService.SendSmsChange(user.getMobile());
    return new Result(true, StatusCode.OK, "发送成功");
  }

  /**
   * 修改密码
   *
   * @param map
   * @return
   */

  @RequestMapping(value = "/changepass", method = RequestMethod.PUT)
  public Result changepass(@RequestBody Map map) {
    JwtUtil jwtUtil = new JwtUtil();
    //先验证合法性
    String token = (String) request.getAttribute("token");
    if (token == null || "".equals(token)) {
      return new Result(false, StatusCode.ACCESSERROR, "权限不足！");
    }
    Claims claims = jwtUtil.parseJWT(token);
    String code = (String) map.get("code");
    LinkedHashMap linkedHashMap = (LinkedHashMap) map.get("user");
    String json = new JSONObject().toJSONString(linkedHashMap);
    User user = JSONObject.parseObject(json, User.class);
    if (!claims.getId().equals(user.getId())) {
      return new Result(false, StatusCode.ACCESSERROR, "权限不足！");
    }
    //得到缓存中的验证码
    String key = "changecode_" + user.getMobile();
    if (redisTemplate.opsForValue().get(key) == null) {
      return new Result(false, StatusCode.ERROR, "请获取手机验证码");
    }
    String checkCodeRedis = (String) redisTemplate.opsForValue().get(key);
    System.out.println(key + ":" + checkCodeRedis);
    if (checkCodeRedis.isEmpty()) {
      return new Result(false, StatusCode.ERROR, "请获取手机验证码");
    }
    if (!checkCodeRedis.equals(code)) {
      return new Result(false, StatusCode.ERROR, "验证码有误");
    }
    //修改
    userService.changePass(user);
    return new Result(true, StatusCode.OK, "修改成功");
  }

  /**
   * 用户个人空间
   *
   * @return
   */
  @RequestMapping(value = "/space", method = RequestMethod.POST)
  public Result space() {
    JwtUtil jwtUtil = new JwtUtil();
    String token = (String) request.getAttribute("token");
    if (token == null || "".equals(token)) {
      return new Result(false, StatusCode.ACCESSERROR, "用户未登录！");
    }
    Claims claims = jwtUtil.parseJWT(token);
    String id = claims.getId();
    User user = userService.findById(id);
    if (user == null) {
      return new Result(false, StatusCode.ACCESSERROR, "无此用户！");
    }
    System.out.println(user.getUsername());
    return new Result(true, StatusCode.OK, "查询成功！", user);
  }

  /**
   * 修改用户信息
   *
   * @param user
   * @return
   */
  @RequestMapping(value = "/changeinfo", method = RequestMethod.POST)
  public Result changeinfo(@RequestBody User user) {
    JwtUtil jwtUtil = new JwtUtil();
    String token = (String) request.getAttribute("token");
    if (token == null || "".equals(token)) {
      return new Result(false, StatusCode.ACCESSERROR, "权限不足！");
    }
    Claims claims = jwtUtil.parseJWT(token);
    if (!claims.getId().equals(user.getId())) {
      return new Result(false, StatusCode.ACCESSERROR, "权限不足！");
    }
    userService.changeInfo(user);
    return new Result(true, StatusCode.OK, "查询成功！", user);
  }

  @RequestMapping(value = "/search/{page}", method = RequestMethod.POST)
  public Result search(@RequestParam String username, @PathVariable int page) {


    Page<User> pages = userService.findSearch(username, page, 10);
    return new Result(true, StatusCode.OK, "查询成功", pages);
  }

  @RequestMapping(value = "/11111", method = RequestMethod.POST)
  public Result o(@RequestBody User user) {
    return new Result(true, StatusCode.OK, "测试");
  }

  @RequestMapping(value = "/getUserById", method = RequestMethod.GET)
  public String getUserById(@RequestParam String id) {
    System.out.println("sfsssssssssssssss" + id);
    User user = userService.findById(id);
    String json = JSON.toJSONString(user);
    return json;
  }

  @RequestMapping(value = "/getUserByName", method = RequestMethod.GET)
  public String getUserByName(@RequestBody String username) {
    User user = userService.searchUser(username);
    if (user == null) {
      return null;
    }
    String json = JSON.toJSONString(user);
    return json;
  }

  @RequestMapping(value = "/upload", method = RequestMethod.POST)
  public Result upload(@RequestParam("file") MultipartFile[] uploads) {


    if (uploads == null) {
      return new Result(true, StatusCode.ERROR, "上传失败！");
    }
    MultipartFile upload = uploads[0];
    UpLoad up = new UpLoad();
    String img = up.upLoadFile(upload, request);
    HttpSession session = request.getSession();
    session.setAttribute("head", img);
    return new Result(true, StatusCode.OK, "上传成功！", img);
  }
  @RequestMapping(value = "/update",method = RequestMethod.PUT)
  public Result update(@RequestBody User user){
      HttpSession session = request.getSession();
      if(session.getAttribute("head")!=null) {
        String head = (String) session.getAttribute("head");
        user.setPhoto(head);
        userService.changeInfo(user);
        return new Result(true,StatusCode.OK,"修改成功！");
      }else{
        userService.changeInfo(user);
        return new Result(true,StatusCode.OK,"修改成功！");
      }

  }



  @RequestMapping(value = "concer/concered_list/{page}",method = RequestMethod.GET)
  public Result concerred_list(@PathVariable int page){
    JwtUtil jwtUtil = new JwtUtil();
    String token = (String) request.getAttribute("token");
    if (token == null || "".equals(token)) {
      return new Result(false, StatusCode.ACCESSERROR, "权限不足！");
    }
    Claims claims = jwtUtil.parseJWT(token);
    String id=claims.getId();
    List<String > ids=userService.concerlist(id);
    Pageable pageable= PageRequest.of(page-1,5);
    Page data=userDao.findByIdIn(ids,pageable);
    return new Result(true, StatusCode.OK,"成功",data);
  }

  @RequestMapping(value = "concer/fans_list/{page}",method = RequestMethod.GET)
  public Result fans_list(@PathVariable int page){
    JwtUtil jwtUtil = new JwtUtil();
    String token = (String) request.getAttribute("token");
    if (token == null || "".equals(token)) {
      return new Result(false, StatusCode.ACCESSERROR, "权限不足！");
    }
    Claims claims = jwtUtil.parseJWT(token);
    String id=claims.getId();
    List<String > ids=userService.fanslist(id);
    Pageable pageable= PageRequest.of(page-1,5);
    Page data=userDao.findByIdIn(ids,pageable);
    return new Result(true, StatusCode.OK,"成功",data);
  }
  @RequestMapping(value = "concer/concer",method = RequestMethod.GET)
  public Result concered(@RequestParam String concered_id){
    JwtUtil jwtUtil = new JwtUtil();
    String token = (String) request.getAttribute("token");
    System.out.println("token is"+token);
    if (token == null || "".equals(token)) {
      return new Result(false, StatusCode.ACCESSERROR, "权限不足！");
    }
    Claims claims = jwtUtil.parseJWT(token);
    String id=claims.getId();
    Concer concer=new Concer();
    concer.setConcered_id(concered_id);
    concer.setFans_id(id);

    User user=userService.findById(concered_id);
    user.setFans(user.getFans()+1);
    userService.changeInfo(user);
    userService.concersomeone(concer);

    return new Result(true, StatusCode.OK,"成功");
  }
  @RequestMapping(value = "concer/notconcer",method = RequestMethod.GET)
  public Result concered_not(@RequestParam String concered_id){

    JwtUtil jwtUtil = new JwtUtil();
    String token = (String) request.getAttribute("token");
    if (token == null || "".equals(token)) {
      return new Result(false, StatusCode.ACCESSERROR, "权限不足！");
    }
    Claims claims = jwtUtil.parseJWT(token);
    String id=claims.getId();
    Concer concer=new Concer();
    concer.setConcered_id(concered_id);
    concer.setFans_id(id);
    User user=userService.findById(concered_id);
    user.setFans(user.getFans()-1);
    userService.changeInfo(user);
    userService.deletesomeone(concer);

    return new Result(true, StatusCode.OK,"成功");
  }
  @RequestMapping(value = "concer/concerstate",method = RequestMethod.GET)
  public Result state(@RequestParam String concered_id){
    JwtUtil jwtUtil = new JwtUtil();
    String token = (String) request.getAttribute("token");
    if (token == null || "".equals(token)) {
      return new Result(false, StatusCode.ACCESSERROR, "权限不足！");
    }
    Claims claims = jwtUtil.parseJWT(token);
    String id=claims.getId();
    Concer concer=new Concer();
    concer.setConcered_id(concered_id);
    concer.setFans_id(id);

Concer concer1=concerMapper.selectState(concer);
if (concer1==null) {
  return new Result(false, StatusCode.OK, "成功");
}
return new Result(true, StatusCode.OK, "成功");
  }
}
